<template>
  <erp-page-form
    ref="erpPageForm"
    :visible-dialog-form.sync="visibleDialog"
    :mode="mode"
    :title="title"
    :form="form"
    :loading="pageLoading"
    :save-loading="buttonLoading"
    :show-save-button="false"
    label-suffix="："
    @close="handleClose"
    @save="handleSave"
  >
    <template slot="tab">
      <el-tab-pane
        v-for="(group, groupIndex) in groupForm"
        :key="groupIndex"
        v-loading="pageLoading"
        :label="group.title || $t('common.erp.form.basicInfo')"
      >
        <el-card shadow="hover">
          <el-row>
            <div
              v-for="(item, index) in group.items"
              :key="index"
            >
              <div v-if="(!item.mode || mode === item.mode || (item.mode instanceof Array && item.mode.indexOf(mode) > -1) && (visibleFunc(item)))">
                <erp-list-page
                  v-if="item.viewType === 'list'"
                  :options.sync="item.options"
                  :extra-data="viewRequest"
                />
                <erp-form-col
                  v-else
                  :label="item.title"
                  :prop="item.field"
                  :label-width="labelWidth(item)"
                  :block="block(item)"
                >
                  <erp-view-item
                    :type="item.viewType"
                    :prop="item.field"
                    :value="item.value"
                    :template="item.template"
                    :row-data="form"
                    :extra="item.extra"
                  />
                </erp-form-col>
              </div>
            </div>
          </el-row>
        </el-card>
      </el-tab-pane>
    </template>
    <template slot="footer-append">
      <!--            <el-button type="primary" @click="handleCreate">创建</el-button>-->
      <!--            <el-button type="primary" @click="handleUpdate">编辑</el-button>-->
    </template>
  </erp-page-form>
</template>

<script>
import Vue from 'vue';
import {Card, FormItem, Input, Radio} from "element-ui";
import ErpPageForm from '@/components/erp/ErpPageForm';
import {base as request} from '@/request';
import {toast, cloneJson} from "@/utils";
import ErpFormCol from "../../../components/erp/ErpPageForm/ErpFormCol";
import ErpViewItem from '@/components/erp/ErpListView/ErpViewItem';

const ErpListPage = () => import('@/components/erp/ErpListPage/ErpListPage');
Vue.use(FormItem);
Vue.use(Radio);
Vue.use(Input);
Vue.use(Card);

/**
 * 展示详情表单
 */
export default {
  name: "ErpListView",
  components: {
    ErpPageForm,
    ErpFormCol,
    ErpViewItem,
    ErpListPage
  },
  props: {
    /**
     * 是否可见【已废弃】
     * @public
     */
    visibleDialog: {
      type: Boolean,
      default: false
    },
    /**
     * 是否正则加载
     * @public
     */
    loading: {
      type: Boolean,
      default: false
    },
    /**
     * 模式是create还是update
     * @public
     */
    mode: {
      type: String,
      default: 'create'
    },
    /**
     * json文件路径
     * @public
     */
    name: {
      type: String,
      default: ''
    },
    /**
     * 额外参数
     * @public
     */
    query: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    return {
      config: {
        name: '',
        primaryKey: '',
        mode: {},
        form: [],
        apiList: {
          view: ""
        }
      },
      initForm: {},
      buttonLoading: false,
      pageLoading: false
    };
  },
  computed: {
    title () {
      return this.config && this.config.mode && this.config.mode[this.mode] ? this.config.mode[this.mode].title : this.$t('common.' + this.mode);
    },
    form () {
      let form = {};
      let formList = this.config.form;
      if (formList && formList.length > 0) {
        for (let i in formList) {
          form[formList[i].field] = formList[i].value;
        }
      }
      return form;
    },
    groupForm () {
      let groupForm = [];
      let form = this.form;
      let formList = cloneJson(this.config.form);
      if (formList && formList.length > 0) {
        for (let i in formList) {
          if (!this.visibleFunc(formList[i])){
            continue;
          }
          if (form[formList[i].field] !== undefined) {
            formList[i].value = form[formList[i].field];
          }
          let group = formList[i].group || '';
          let hasGroup = false;
          if (groupForm && groupForm.length > 0) {
            for (let j in groupForm) {
              let groupTitle = groupForm[j].title || '';
              if (group === groupTitle) {
                hasGroup = true;
                groupForm[j].items.push(formList[i]);
                break;
              }
            }
          }
          if (!hasGroup) {
            let groupRow = {
              title: group,
              items: [formList[i]]
            };
            groupForm.push(groupRow);
          }
        }
      }
      return groupForm;
    },
    primaryKeyValue () {
      let primaryKey = this.config.primaryKey;
      let query = this.query;
      return query[primaryKey] || '';
    },
    block () {
      return function (item) {
        let times = item === undefined || item.col === undefined ? null : item.col.times;
        if(!times || isNaN(times) || times <= 0) {
          times = 1;
        }
        return times;
      };
    },
    labelWidth () {
      return function (item) {
        return item === undefined || item.col === undefined ? null : item.col.labelWidth;
      };
    },
    viewRequest () {
      return {[this.config.primaryKey]: this.primaryKeyValue};
    }
  },
  watch: {
    visibleDialog: {
      handler (n) {
        if (n) {
          // this.getDetail()
        }
      },
    },

  },
  mounted () {
    this.getConfig();
  },
  methods: {
    /**
     * 关闭表单
     * @private
     */
    handleClose() {
      /**
       * 通知父组件关闭表单
       */
      this.$emit('update:visibleDialog', false);
    },
    /**
     * 获取配置文件
     * @private
     */
    getConfig () {
      this.config = require('@public/data/' + this.name + '/view.json');
      this.getDetail();
    },
    /**
     * 请求获取表单默认值
     * @private
     */
    getDetail () {
      let viewRequest = {[this.config.primaryKey]: this.primaryKeyValue};
      let viewApi = this.config && this.config.apiList && this.config.apiList.view ? this.config.apiList.view : '';
      this.pageLoading = true;
      request.post(viewApi, viewRequest)
        .then(res => {
          let form = res.data;
          let configForm = cloneJson(this.config.form);
          if (configForm && configForm.length > 0) {
            for (let i in configForm) {
              let field = configForm[i].field;
              if (form[field] !== undefined) {
                configForm[i].value = form[field];
              }
            }
          }
          this.config.form = configForm;
          this.pageLoading = false;
        })
        .catch(() => {
          this.pageLoading = false;
        });
    },
    /**
     * 保存表单，只在添加和编辑时使用
     * @private
     */
    handleSave(form) {
      this.buttonLoading = true;
      if (this.mode === 'create') {
        const {create} = require('@/api/' + this.name);
        create(form)
          .then(() => {
            toast({
              message: this.$t('common.createSuccess'),
              type: 'success'
            });
            this.$emit('after-save');
            this.handleClose();
            this.buttonLoading = false;
          })
          .catch(() => {
            this.buttonLoading = false;
          });
      } else if (this.mode === 'update') {
        const {update} = require('@/api/' + this.name);
        update(form)
          .then(() => {
            toast({
              message: this.$t('common.updateSuccess'),
              type: 'success'
            });
            this.$emit('after-save');
            this.handleClose();
            this.buttonLoading = false;
          })
          .catch(() => {
            this.buttonLoading = false;
          });
      }
    },
    /**
     *
     * @private
     */
    handleCreate () {
    },
    /**
     * 判断表单项是否可见
     * @private
     */
    visibleFunc (item) {
      if (item.visibleFunction) {
        let form = this.form;
        let field = item.field;
        try{
          return new Function('form','field', item.visibleFunction )(form, field);
        }catch(e) {
          return true;
        }
      }
      return true;
    },
    /**
     * 过滤掉非当前模式下的字段
     * @private
     */
    filterFieldByMode (item) {
      let itemMode = item.mode;
      if (itemMode === undefined) {
        return true;
      }
      let mode = this.mode;
      return !!((itemMode instanceof Array && itemMode.indexOf(mode) > -1) && this.visibleFunc(item));
    }
  }
};
</script>

<style lang="scss" scoped>

</style>
